package com.zzyy.study.stack;

import java.util.Scanner;

/**
 * Description:
 * <p>
 * ClassName: ArrayStackDemo
 * date: 2021/2/24 10:01
 *
 * @author zzjx
 * @version 1.0
 * @since JDK 1.8
 */
public class ArrayStackDemo {
    private int maxSize;
    private int[] stack;
    private int top = -1; //top表示栈顶，初始化为-1
    //构造器
    public ArrayStackDemo(int maxSize){
        this.maxSize = maxSize;
        stack = new int[maxSize];
    }
    //栈满
    public boolean isFull(){
        return top == maxSize-1;
    }
    //栈空
    public boolean isEmpty(){
        return top == -1;
    }
    //入栈
    public void push(int value){
        //先判断栈是否满
        if(isFull()){
            System.out.println("栈满");
            return;
        }
        top++;
        stack[top] = value;
    }
    //出栈 ，将栈顶的数据返回
    public int pop() {
        //先判断栈是否空
        if(isEmpty()){
            System.out.println();
            //抛出异常
            throw new RuntimeException("异常");
        }
        int value = stack[top];
        top--;
        return value;
    }
    //显示栈的情况[遍历栈]
    public void list(){
        if(isEmpty()){
            System.out.println("栈空，没有数据~~");
            return;
        }
        for (int i = top; i >= 0; i--) {
            System.out.printf("stack[%d]=%d\n",i,stack[i]);
        }
    }

    public static void main(String[] args) {
        ArrayStackDemo stack = new ArrayStackDemo(4);
        String key = "";
        boolean loop =true;
        Scanner scanner = new Scanner(System.in);
        while (loop){
            System.out.println("s: 表示显示栈");
            System.out.println("e: 退出程序");
            System.out.println("push: 表示入栈");
            System.out.println("pop: 表示出栈");
            key = scanner.next();
            switch (key){
                case "s":
                    stack.list();
                    break;
                case "push":
                    System.out.println("请输入一个数");
                    int value = scanner.nextInt();
                    stack.push(value);
                    break;
                case "pop":
                    stack.pop();
                    break;
                case "exit":
                    loop=false;
                    scanner.close();
                    break;
                default:
                    loop=false;
                    break;
            }
        }
    }
}
